<script setup lang="ts">
import { Search, Refresh, CirclePlus, Download } from "@element-plus/icons-vue"
import { deleteEvalDataApi, downloadEvalApi, getEvalDataApi } from "@/api/eval/index"
import { ElMessage, ElMessageBox, FormInstance } from "element-plus"
import { usePagination } from "@/hooks/usePagination"
import CreateOrUpdate from "./create-or-update.vue"
import { FormTypeEnum, AlgoTypeEnum } from "@/constants/other-keys"
import { reactive, ref, watch, nextTick, inject } from "vue"
import { EvalTableData } from "@/api/eval/types/eval"

const parent = inject<{ activeName: AlgoTypeEnum }>("parent")
const loading = ref<boolean>(false)
const searchMore = ref<boolean>(false)
const searchData = reactive({
  eval_model_name: undefined,
  publish_time: undefined,
  end_time: undefined
})
const dialogType = ref<FormTypeEnum>(FormTypeEnum.CREATE)
const editDialogRef = ref()
const curId = ref<string>()
const { paginationData, handleCurrentChange, handleSizeChange } = usePagination()

const handleSearchMore = () => {
  searchData.publish_time = undefined
  searchData.end_time = undefined
  searchMore.value = !searchMore.value
}

const dialogVisible = ref(false)

//#region 详情
const handleView = (row: EvalTableData) => {
  nextTick(() => {
    curId.value = row.eval_model_id
    dialogType.value = FormTypeEnum.VIEW
    dialogVisible.value = true
  })
}
//#endregion
//#region 增
const handleCreate = () => {
  nextTick(() => {
    curId.value = undefined
    dialogType.value = FormTypeEnum.CREATE
    dialogVisible.value = true
  })
}
//#endregion
//#region 删
const handleDelete = (row: EvalTableData) => {
  ElMessageBox.confirm(`正在删除评估模型：${row.eval_model_name}，确认删除？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    row.eval_model_id &&
      deleteEvalDataApi(row.eval_model_id).then(() => {
        ElMessage.success("删除成功")
        getTableData()
      })
  })
}
//#endregion

//#region 改
// const handleUpdate = (row: EvalTableData) => {
//   nextTick(() => {
//     dialogType.value = FormTypeEnum.EDIT
//     curId.value = row.eval_model_id
//     dialogVisible.value = true
//   })
// }
//#endregion
//#region 查
const tableData = ref<EvalTableData[]>([])
const searchFormRef = ref<FormInstance | null>(null)
const getTableData = () => {
  loading.value = true
  parent &&
    getEvalDataApi({
      size: paginationData.pageSize,
      current_page: paginationData.currentPage,
      eval_model_name: searchData.eval_model_name || undefined,
      eval_model_type: parent.activeName,
      publish_time: searchData.publish_time || undefined,
      end_time: searchData.end_time || undefined
    })
      .then(({ data }) => {
        tableData.value = data.page_info
        paginationData.total = data.total_count
      })
      .catch(() => {
        tableData.value = []
      })
      .finally(() => {
        loading.value = false
      })
}
const handleSearch = () => {
  paginationData.currentPage === 1 ? getTableData() : (paginationData.currentPage = 1)
}
const resetSearch = () => {
  searchFormRef.value?.resetFields()
  handleSearch()
}
//#endregion

//#region
const handleDownload = (row: EvalTableData) => {
  row.eval_model_id &&
    downloadEvalApi(row.eval_model_id).then((res) => {
      const blob = new Blob([res.data])
      const contentPosition = res.headers["content-disposition"]
      if (contentPosition) {
        const match = contentPosition.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/)
        const fileName = match[1].replace(/['"]/g, "")
        if ("download" in document.createElement("a")) {
          const elink = document.createElement("a")
          elink.download = fileName
          elink.style.display = "none"
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href)
          document.body.removeChild(elink)
        }
      } else {
        ElMessage.error("下载失败")
      }
    })
}
//#endregion

const closeDialog = (param: string | undefined) => {
  dialogVisible.value = false
  if (param && param == "refresh") getTableData()
}

/** 监听分页参数的变化 */
watch([() => paginationData.currentPage, () => paginationData.pageSize], getTableData, { immediate: true })

watch(
  () => parent && parent.activeName,
  () => getTableData
)
</script>

<template>
  <el-card v-loading="loading" shadow="never" class="search-wrapper">
    <el-form ref="searchFormRef" :inline="true" :model="searchData">
      <el-form-item prop="eval_model_name" label="评估模型名称">
        <el-input v-model="searchData.eval_model_name" placeholder="请输入" />
      </el-form-item>
      <el-form-item>
        <el-button link type="primary" @click="handleSearchMore">{{ searchMore ? "收起" : "更多" }}</el-button>
        <el-button type="primary" :icon="Search" @click="handleSearch">查询</el-button>
        <el-button :icon="Refresh" @click="resetSearch">重置</el-button>
      </el-form-item>
      <el-row v-if="searchMore">
        <el-form-item prop="publish_time" label="发布时间">
          <el-date-picker
            v-model="searchData.publish_time"
            value-format="YYYY-MM-DD"
            type="date"
            placeholder="请选择"
          />
        </el-form-item>
        <el-form-item prop="end_time" label="截至时间">
          <el-date-picker v-model="searchData.end_time" value-format="YYYY-MM-DD" type="date" placeholder="请选择" />
        </el-form-item>
      </el-row>
    </el-form>
  </el-card>
  <div class="toolbar-wrapper">
    <div>
      <el-button type="primary" :icon="CirclePlus" @click="handleCreate">新增评估模型</el-button>
    </div>
  </div>
  <el-row v-loading="loading" shadow="never" :gutter="20">
    <el-col :xs="12" :sm="8" :md="8" :lg="6" :xl="5" v-for="(item, index) in tableData" :key="index">
      <el-card class="card-item" body-class="card-item body">
        <template #header>
          <div class="card-header flex-between">
            <el-space class="flex-vc">
              <el-icon><Calendar /></el-icon>
              <el-text>{{ item.create_time }}</el-text>
            </el-space>
            <el-link :underline="false" v-throttle="() => handleDownload(item)">
              <el-icon :size="18"><Download /></el-icon>
            </el-link>
          </div>
        </template>
        <div class="card-body">
          <div class="flex-between relation">
            <el-space class="flex-vc">
              <el-text size="large" class="w-150px mb-2" truncated>
                {{ item.eval_model_name }}
              </el-text>
            </el-space>
            <el-space class="flex-vc card-operate">
              <el-link :underline="false" @click="handleView(item)">
                <el-icon :size="18"><View /></el-icon>
              </el-link>
              <!-- <el-link :underline="false" @click="handleUpdate(item)">
                <el-icon :size="18"><Edit /></el-icon>
              </el-link> -->
              <el-link :underline="false" @click="handleDelete(item)">
                <el-icon :size="18"><Delete /></el-icon>
              </el-link>
            </el-space>
          </div>
          <p class="describe">
            <el-text type="info" line-clamp="2">
              {{ item.eval_model_describe }}
            </el-text>
          </p>
        </div>
        <template #footer>
          <div class="card-footer flex-between">
            <el-space class="flex-vc">
              <el-icon><UserFilled /></el-icon>
              <el-text>{{ item.create_user.user_name }}</el-text>
            </el-space>
            <el-tag type="info" effect="plain">{{ item.create_user.user_position }}</el-tag>
          </div>
        </template>
      </el-card>
    </el-col>
  </el-row>
  <div class="pager-wrapper">
    <el-pagination
      background
      :layout="paginationData.layout"
      :page-sizes="paginationData.pageSizes"
      :total="paginationData.total"
      :page-size="paginationData.pageSize"
      :currentPage="paginationData.currentPage"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>

  <CreateOrUpdate
    ref="editDialogRef"
    :id="curId"
    :dialog-type="dialogType"
    :visible="dialogVisible"
    @closeDialog="closeDialog"
  />
</template>
<style lang="scss" scoped>
@import "@/styles/custom.scss";
</style>
